package com.cool.config.springsecurity.callback;

import cn.hutool.json.JSONUtil;
import com.cool.bo.sysmanage.stuff.UserLoginBo;
import com.cool.common.CommonResult;
import com.cool.common.ResponseCode;
import com.cool.utils.SpringContextUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Jiangmanman
 */
@Configuration
@Slf4j
public class SuccessHandlerConfig implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
//        ObjectMapper objectMapper = SpringContextUtil.getBean(ObjectMapper.class);
//
//        String ajax = request.getHeader("X-Requested-With");
//        if(!Strings.isNullOrEmpty(ajax) && Objects.equals(ajax.trim(),ajax)){
//            log.info("验证成功:响应Json数据");
//            //响应Json数据
//            String jsonString = objectMapper.writeValueAsString(CommonResult.newCommonResult().setCode(200).setData(authentication).setMsg("登录成功"));
//            response.setContentType("application/json;charset=utf-8");
//            response.getWriter().write(jsonString);
//            response.getWriter().flush();
//
//        }else {
//            log.info("验证成功:开始重定向");
//
//            response.sendRedirect("/home");
//        }


        UserLoginBo userLoginBo = (UserLoginBo) authentication.getPrincipal();


        request.getSession().setAttribute("userLoginBo", userLoginBo);

        response.setContentType("application/json;charset=utf-8");

        CommonResult commonResult = CommonResult.newCommonResult().setCode(ResponseCode.USER_LOGIN_SUCCESS).setMsg("登录成功").setData(userLoginBo);

        response.getWriter().write(JSONUtil.toJsonStr(commonResult));

        response.getWriter().flush();

        response.getWriter().close();
    }
}
